﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Media.Animation;
using System.Windows.Media;
using System.Windows;
using System.Windows.Controls;
using System.IO;

namespace Yxinmt.Windows.Meeting
{
    public class Utils
    {
        public static Dictionary<string, object> CloneDictionary(Dictionary<string, object> dict, List<Entity.PropertySet> propertyList = null)
        {
            Dictionary<string, object> dict2 = new Dictionary<string, object>();
            Entity.PropertySet property = null;
            bool blExists = false;

            string key = dict.ContainsKey("name") ? dict["name"].ToString() : string.Empty;

            foreach (var kvp in dict)
            {
                if (kvp.Value is Dictionary<string, object>)
                {
                    blExists = false;
                    if (!string.IsNullOrEmpty(key) && propertyList != null)
                    {
                        property = propertyList.Where(w => w.Key == key && kvp.Key == w.Name).FirstOrDefault();
                        if (property != null) { blExists = true; }
                    }
                    if (!blExists)
                    {
                        dict2[kvp.Key] = CloneDictionary(kvp.Value as Dictionary<string, object>, propertyList);
                    }
                }
                else if (kvp.Value is List<Dictionary<string, object>>)
                {

                    blExists = false;
                    if (!string.IsNullOrEmpty(key) && propertyList != null)
                    {
                        property = propertyList.Where(w => w.Key == key && kvp.Key == w.Name).FirstOrDefault();
                        if (property != null) { blExists = true; }
                    }

                    if (!blExists) dict2[kvp.Key] = (from a in kvp.Value as List<Dictionary<string, object>>
                                                     select CloneDictionary(a, propertyList)).ToList();
                }
                else
                {
                    dict2[kvp.Key] = kvp.Value;
                }
            }

            if (propertyList != null && !string.IsNullOrEmpty(key))
            {
                propertyList.Where(w => w.Key == key).ToList().ForEach(p =>
                {
                    if (p.IsPropertyName && p.Value != null && dict2.ContainsKey((string)p.Value)) dict2[p.Name] = dict2[(string)p.Value];
                    else dict2[p.Name] = p.Value;
                });
            }

            return dict2;
        }


        public static void SetLoadingAnimation(Image img)
        {
            RotateTransform rotateTransform = new RotateTransform();
            rotateTransform.CenterX = 24;
            rotateTransform.CenterY = 24;
            // 将 RotateTransform 应用到 Image 的 RenderTransform 属性
            img.RenderTransform = rotateTransform;

            // 创建 Storyboard
            Storyboard rotateStoryboard = new Storyboard();

            // 创建 DoubleAnimation
            DoubleAnimation doubleAnimation = new DoubleAnimation
            {
                From = 0,
                To = 360,
                Duration = TimeSpan.FromSeconds(1),
                RepeatBehavior = RepeatBehavior.Forever
            };

            // 设置动画的目标属性
            Storyboard.SetTarget(doubleAnimation, img);
            Storyboard.SetTargetProperty(doubleAnimation, new PropertyPath("(UIElement.RenderTransform).(RotateTransform.Angle)"));

            // 将动画添加到 Storyboard
            rotateStoryboard.Children.Add(doubleAnimation);

            // 启动 Storyboard
            rotateStoryboard.Begin();
        }

        public static string DownloadFile(string url)
        {
            try
            {
                string fileName = string.Empty;
                string dir = AppDomain.CurrentDomain.BaseDirectory + "res" + "\\" + Utility.Common.ComputeStringMd5(url);
                if (!Directory.Exists(dir)) Directory.CreateDirectory(dir);

                var names = url.Split('/');
                var name = names[names.Length - 1];
                fileName = dir + "\\" + name;

                if (File.Exists(fileName)) return fileName;

                var bs = Utility.Common.GetHttpFileBytes(url);
                if (bs.Length == 0) throw new Exception("文件为空文件！");

                Utility.Common.SaveFile(bs, fileName);

                return fileName;
            }
            catch (Exception ex)
            {
                ex = Utility.Common.GetInnerException(ex);
                throw new Exception("加载文件失败：" + ex.Message);
            }
        }

        public static byte[] DownloadFileBytes(string url)
        {
            try
            {
                string fileName = string.Empty;
                string dir = AppDomain.CurrentDomain.BaseDirectory + "res" + "\\" + Utility.Common.ComputeStringMd5(url);
                if (!Directory.Exists(dir)) Directory.CreateDirectory(dir);

                var names = url.Split('/');
                var name = names[names.Length - 1];
                fileName = dir + "\\" + name;

                if (File.Exists(fileName))
                {
                    return File.ReadAllBytes(fileName);
                }

                var bs = Utility.Common.GetHttpFileBytes(url);
                if (bs.Length == 0) throw new Exception("文件为空文件！");

                Utility.Common.SaveFile(bs, fileName);

                return bs;
            }
            catch (Exception ex)
            {
                ex = Utility.Common.GetInnerException(ex);
                throw new Exception("加载文件失败：" + ex.Message);
            }
        }

        public static string CopyFile(Dictionary<string,string> fileNameDict, string fileName)
        {
            string fileName2 = string.Empty;
            if (fileNameDict.ContainsKey(fileName))
            {
                fileName2 = fileNameDict[fileName];
                if (File.Exists(fileName2)) return fileName2;
            }

            var ns = fileName.Split('\\');
            List<string> dirs = new List<string>();
            string name = string.Empty;
            for (int i = 0; i < ns.Length; i++)
            {
                if (i == ns.Length - 1) name = ns[i];
                else dirs.Add(ns[i]);
            }
            string dir = string.Join("\\", dirs);

            var files = Directory.GetFiles(dir);
            if (files.Length > 1)
            {
                foreach (var f in files)
                {
                    if (!f.ToLower().Equals(fileName.ToLower()))
                    {
                        try
                        {
                            File.Delete(f);
                        }
                        catch
                        {

                        }
                    }
                }
            }

            fileName2 = dir + "\\" + Guid.NewGuid().ToString().Substring(0, 8) + name;

            File.Copy(fileName, fileName2, true);
            fileNameDict[fileName] = fileName2;
            return fileName2;
        }
    }
}
